package cn.kzgg.basic.controller;

import cn.kzgg.basic.exception.BusinessException;
import cn.kzgg.basic.util.AjaxResult;
import cn.kzgg.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 分布式文件接口
 * 1.上传接口
 *
 * 2.删除接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     *文件上传接口
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            String filename = file.getOriginalFilename();//文件的原始名字全路径
            String extName = filename.substring(filename.lastIndexOf(".") + 1);//文件扩展名
            String path = FastdfsUtil.upload(file.getBytes(),extName);
            return AjaxResult.show().setResultObj(path);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.show().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.show().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

    /**
     * 删除
     * @param path
     * @return
     */
    @DeleteMapping//从/group1开始  /group1/M00/00/07/CgAIC2KmF9yAP_wUAAT_gDSW89c269.jpg
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1);//从下标1开始  group1/M00/00/07/CgAIC2KmF9yAP_wUAAT_gDSW89c269.jpg
            String group = pathTmp.substring(0,pathTmp.indexOf("/")); //  /group1
            String filename = pathTmp.substring(pathTmp.indexOf("/")+1);
            FastdfsUtil.delete(group,filename);
            return AjaxResult.show();
        } catch (BusinessException e) {//我们自己的业务异常，我们需要自己处理
            e.printStackTrace();
            return AjaxResult.show().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.show().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }



}
